package com.example.tuter.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Looper;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.tuter.R;
import com.example.tuter.activity.util.SendPhotoActivity;
import com.example.tuter.entity.Message;
import com.example.tuter.util.httpUtil.HttpCodeConstant;
import com.example.tuter.util.httpUtil.HttpFunction.UploadAPI;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ImageUploadHelper {
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;

    private static final String UPLOAD_SUCCESS = "图片上传成功";
    private static final String UPLOAD_FAILED = "图片上传失败,请重试";
    private static final String ON_UPLOADING = "图片上传中";
    private static final String MEDIA = "com.android.providers.media.documents";
    private static final String DOWNLOADS = "com.android.providers.downloads.documents";
    private static final String PUBLIC_DOWNLOADS = "content://downloads/public_downloads";
    private static final String CONTENT = "content";
    private static final String FILE = "file";

    private static final String FAILED_GET_IMAGE = "failed to get image";


    private final Activity activity;
    private final SendPhotoActivity sendPhotoActivity;
    //发送按钮
    ImageView imageviewSend;
    //选择图片按钮
    ImageView imageViewChoosePhoto;
    //返回按钮
    ImageView imageView_back;
    private String uploadImageUri;


    public String getUploadImageUri() {
        return uploadImageUri;
    }

    public ImageUploadHelper(Activity activity, SendPhotoActivity sendPhotoActivity, ImageView imageviewSend, ImageView imageViewChoosePhoto, ImageView imageView_back) {
        this.activity = activity;
        this.imageviewSend = imageviewSend;
        this.imageViewChoosePhoto = imageViewChoosePhoto;
        this.imageView_back = imageView_back;
        this.sendPhotoActivity = sendPhotoActivity;
        setChoosePhoto();
        setBack();
        setSend();
    }

    //打开相册
    public void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        activity.startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @TargetApi(19)
    public void handleImageOnKitKat(Intent data, ImageView picture) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(activity, uri)) {
            //如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if (MEDIA.equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if (DOWNLOADS.equals(uri.
                    getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse(PUBLIC_DOWNLOADS), Long.parseLong(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if (CONTENT.equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if (FILE.equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImageAndUpload(imagePath, picture); // 根据图片路径显示上传图片
    }


    //两个版本的图片上传
    public void handleImageBeforeKitKat(Intent data, ImageView picture) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImageAndUpload(imagePath, picture);
    }

    @SuppressLint("Range")
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = activity.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.
                        Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //展示图片并上传服务器
    private void displayImageAndUpload(String imagePath, ImageView picture) {
        if (imagePath != null) {

            File file = new File(imagePath);

            Toast.makeText(activity, ON_UPLOADING, Toast.LENGTH_SHORT).show();
            UploadAPI uploadAPI = Constant.r.create(UploadAPI.class);

            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("file", file.getName(), imageBody);
            retrofit2.Call<Message<String>> uploadCall = uploadAPI.uploadPicture(imageBodyPart);

            //访问接口，上传图片，获取图片链接
            uploadCall.enqueue(new retrofit2.Callback<Message<String>>() {
                @Override
                public void onResponse(retrofit2.Call<Message<String>> call, retrofit2.Response<Message<String>> response) {
                    Message<String> body = response.body();
                    if (body.getCode() == HttpCodeConstant.SUCCESS.getValue()) {
                        //更新图片路径
                        uploadImageUri = body.getData();
                        Toast.makeText(activity, UPLOAD_SUCCESS, Toast.LENGTH_SHORT).show();
                        //图片加载
                        Glide.with(activity).load(imagePath).placeholder(R.drawable.ic_launcher_background).override(400, 400).crossFade().into(picture);
                    } else {
                        Toast.makeText(activity, UPLOAD_FAILED, Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onFailure(retrofit2.Call<Message<String>> call, Throwable t) {
                    Toast.makeText(activity, UPLOAD_FAILED, Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Looper.prepare();
            Toast.makeText(activity, FAILED_GET_IMAGE, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }

    public void setBack() {
        imageView_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.finish();
            }
        });
    }

    public void setSend() {
        imageviewSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendPhotoActivity.sendPhotoContent();
            }
        });
    }

    public void setChoosePhoto() {
        imageViewChoosePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    //打开相册
                    openAlbum();
                }
            }
        });
    }
}
